package org.company.tool.tools;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.company.tool.bean.ColumnBean;
import org.company.tool.bean.Entity;
import org.company.tool.service.EntityTransfer;
import org.company.tool.service.imp.OracleEntityTransfer;
import org.company.tool.util.FreemarkerUtil;
import org.company.tool.util.StringUtil;

import freemarker.template.TemplateException;

public abstract class Generator {
    
    private Map<String, Object> context = new HashMap<String, Object>();
    
    protected EntityTransfer entityTransfer = new OracleEntityTransfer();
    
    protected Entity entity = null;
    
    /**
     * @return the entityTransfer
     */
    public EntityTransfer getEntityTransfer() {
        return entityTransfer;
    }

    /**
     * @param entityTransfer the entityTransfer to set
     */
    public void setEntityTransfer(EntityTransfer entityTransfer) {
        this.entityTransfer = entityTransfer;
    }
    
    public void init() throws SQLException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ColumnBean> columnList = 
                this.entityTransfer.parseColumn(this.entity.getTableName());
        context.put("entityBean", entity);
        context.put("columnBeanList", columnList);
        context.put("createdate", sdf.format(new Date()));
    }
    
    public void generator(String fmtUri,OutputStream out) {
        this.generator(fmtUri, new OutputStreamWriter(out));
    }
    
    public void generator(String fmtUri,Writer writer) {
        try {
            FreemarkerUtil.getInstance().mergeTemplate(fmtUri, writer, this.context);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
